package com.example.rwq_test.agent;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 *  1. 主要是在通过继承来实现方法: java.util.ArrayList#removeRange(int, int)
 *  2. java.util.ArrayList#removeRange(int, int)是一个protected方法通过继承调用即可；
 *  3. 模拟多个线程向list中添加元素， 一个线程批量取出元素处理
 *
 * @Author renweiqiang
 * @Date 2024/4/19 下午5:21
 */
public class ProtectedMethodExtends {

    private static final EntityList<Integer> list = new EntityList<>();

    public static void main(String[] args) throws InterruptedException {
        // 添加数据
        addData();

        TimeUnit.MILLISECONDS.sleep(500);

        //处理数据
        handleData();
    }

    /**
     * 处理数据
     */
    private static void handleData() {
        new Thread(() -> {
            // 获取数据
            ArrayList<Integer> list1 = new ArrayList<>(list);
            try {
                //模拟处理业务
                TimeUnit.MILLISECONDS.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            // 移除数据
            list.removeRange(0, list1.size());
        }).run();
    }

    /**
     * 添加数据
     */
    private static void addData() {
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int i1 = 0; i1 < 500000; i1++) {
                    list.add(i1);
                    try {
                        TimeUnit.MILLISECONDS.sleep(10);
                    } catch (InterruptedException e) {

                    }
                }
            }).run();
        }
    }

    /**
     * 自定义实体类List
     *
     * @param <E>
     */
    static class EntityList<E> extends ArrayList<E> {
        private static final long serialVersionUID = 2254981961538422491L;

        public EntityList(int initialCapacity) {
            super(initialCapacity);
        }

        public EntityList() {
        }

        /**
         * 安全移除
         *
         * @param fromIndex index of first element to be removed
         * @param toIndex index after last element to be removed
         */
        @Override
        public synchronized void removeRange(int fromIndex, int toIndex) {
            super.removeRange(fromIndex, toIndex);
        }

        /**
         * 安全添加
         *
         * @param e element whose presence in this collection is to be ensured
         * @return
         */
        @Override
        public synchronized boolean add(E e) {
            return super.add(e);
        }
    }
}
